package com.cyandpos.pad.pay.payList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.FrameLayout;

import com.changyi.device.printer.PrintManagerLib;
import com.cyandpos.pad.activity.PayActivity;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.posdata.O2OPayDetail;
import com.cyandpos.pad.posdata.POS_JHRequest;
import com.cyandpos.pad.posdata.PosJHResponse;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.DateUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.SDTools;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.UUID;


/**
 * Created by zx on 2017/3/13.
 */

public class JHPay extends FrameLayout {
    private PayActivity homeAct;
    private int pmtId=0;//付款方式的ID
    private Timer mTimer = new Timer();
    private TicketInfo mTicket;
    //    private PosO2ORequest posO2oRequest;
//    private PosO2ORequest_Work posO2oRequest_work;
//    private PosO2ORequest_Base posO2oRequest_base;
    private POS_JHRequest mWXRequest;
    private int payMoney;
    private int unavailNum;
    private String wxCode="";
    private String jlbh;
    private boolean isOne = false;
    private int payType;

    private Handler o2oQueryHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:{
//                    mWXRequest.setOutTradeNo(mTicket.getPosId() + jlbh
//                            + ToastUtils.getString(Calendar.getInstance(), "HHmmssSSS"));
                    if(!TextUtils.isEmpty(mTicket.getOldOrderNo())){
                        mWXRequest.setTradeType("SJ_REFUNDQUREY");
                    }else {
                        mWXRequest.setTradeType("SJ_SALEQUREY");
                    }
                    if (queryNumber >= 20){
                        dissmissWaitDialog();
                        new AlertDialog.Builder(homeAct).setCancelable(false).setTitle("查询失败是否继续查询？")
                                .setNegativeButton("否", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        queryNumber = 0;
                                    }
                                }).setPositiveButton("是", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                o2oQueryHandler.sendEmptyMessageDelayed(0, 5000);
                                queryNumber = 0;
                                showWaitDialog("查询中...");
                            }
                        }).setCancelable(false).create().show();
                        }else {
                            wxRequest();
                        }
                }
                break;

                case 2:{
                    dissmissWaitDialog();
                    //更新
//                    mWXRequest.setOutTradeNo(mTicket.getPosId() + jlbh
//                            + ToastUtils.getString(Calendar.getInstance(), "HHmmssSSS"));

                    if(!TextUtils.isEmpty(mTicket.getOldOrderNo())){
                        mWXRequest.setTradeType("SJ_REFUNDQUREY");
                    }else {
                        mWXRequest.setTradeType("SJ_SALEQUREY");
                    }
                    new AlertDialog.Builder(homeAct).setCancelable(false).setTitle("查询失败是否继续查询？")
                            .setNegativeButton("否", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    queryNumber = 0;
                                }
                            }).setPositiveButton("是", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            o2oQueryHandler.sendEmptyMessageDelayed(0, 5000);
                            queryNumber = 0;
                            showWaitDialog("查询中...");
                        }
                    }).setCancelable(false).create().show();
                }
                break;
                default:
                    break;
            }

        }

    };

    public JHPay(PayActivity context){
        super(context);

    }

    public JHPay(PayActivity context, TicketInfo ticket, int mSelectedPmtId, int payType, int pay, String buyerCode) {
        super(context);
        homeAct = context;
        this.pmtId = mSelectedPmtId;
        this.payType = payType;
        this.payMoney = pay;
        this.mTicket = ticket;
        this.wxCode = buyerCode;
        mWXRequest = new POS_JHRequest();
        unavailNum= 0;
    }


    public void wxConsume() {
        mProgressDialog = new ProgressDialog(homeAct);
        if (CommonUtils.isNullOrEmpty(wxCode)){
            return;
        }
        jlbh = mTicket.getJlbh() + "";
        if (jlbh.length() <= 8) {
            jlbh = CommonUtils.formatStr(jlbh, 8);
        }
        if (payMoney == 0) {
            ToastUtils.showMsg(homeAct, "请正确输入金额");
            return;
        }
        mWXRequest.setInterfaceId("1");
        mWXRequest.setChannelID("b6");

        mWXRequest.setStoreId(mTicket.getStoreCode() + "");


        mWXRequest.setTotalFee(payMoney + "");
        mWXRequest.setOutTradeNo(mTicket.getSktno() + jlbh
                + new SimpleDateFormat("HHmmssSSS").format(Calendar.getInstance().getTime()));
        mWXRequest.setSktno(mTicket.getSktno());
        mWXRequest.setJlbh(mTicket.getJlbh() + "");
        mWXRequest.setSkfs(pmtId + "");
//        mWXRequest.setOperator1(mTicket.getCasherInfo().getPersonCode());
        mWXRequest.setGuid(UUID.randomUUID().toString());
        mWXRequest.setStoreId(ErpCommonData.storeCode);

        if(!TextUtils.isEmpty(mTicket.getOldOrderNo())){
            mWXRequest.setBuyerCode(wxCode);
            mWXRequest.setTradeType("SJ_REFUND");
            mWXRequest.setRefundNo(wxCode);

            if (TextUtils.isEmpty(mWXRequest.getRefundNo())) {
                ToastUtils.showMsg(homeAct, "未获取到原流水号!");
                return;
            }
        }else {
            mWXRequest.setBuyerCode(wxCode);
            if (homeAct.isWxOrZfBBL){
                mWXRequest.setTradeType("SJ_SALEQUREY");
                mWXRequest.setAttach("QUERY");
                mWXRequest.setOutTradeNo(wxCode);
            }else {
                mWXRequest.setTradeType("SJ_BS");
            }
        }
        mWXRequest.setOrderNo(mTicket.getOrderNo());


        wxRequest();
    }

    private void wxRequest() {
        showWaitDialog("交易查询中...");
        PosHttpManager.sjConsume(mWXRequest, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                BaseResponse<PosJHResponse> loginRes = BaseResponse.fromJson(response.toString(),PosJHResponse.class);
                if(loginRes.getCode().equals("0")){
                    PosJHResponse resData = loginRes.getData();
                    if ("1".equals(resData.getReturnCode())){
                        ToastUtils.showMsg(homeAct, "支付成功");
                        dissmissWaitDialog();
                        int traceType = (mTicket.getOldOrderNo()!=null && mTicket.getOldOrderNo().length()>0) ? 1 : 0;
                        O2OPayDetail item = handleO2OData(resData,traceType);
                        SDTools.writeO2OTicket(item,4);
                        for(int i=0;i<Integer.parseInt(ErpCommonData.allvpayPrintNum);i++) {
                            //打印
                            PrintManagerLib.initPrinter(homeAct, CommonUtils.getSystemModel())
                                    .initDevice()
                                    .printList(createHeadByTicket(resData, 1));
                        }
//                        YhkCardItem xykItem = new YhkCardItem();
//                        xykItem.setAmount(resData.getActTotalFee());
//                        xykItem.setLsh(resData.getTransactionId());
//                        xykItem.setSkfs(pmtId + "");
//                        xykItem.setYhje(resData.getCouponFee());
//                        xykItem.setYhje_shop(resData.getCouponFee_Shop());
//                        xykItem.setPayType(payType + "");
                        //同步付款
                        completeTanpay(item);
                    }else if("2".equals(resData.getReturnCode())){
                        queryNumber++;
                        showWaitDialog("交易查询中...");
                        o2oQueryHandler.sendEmptyMessageDelayed(0, 3000);
                    }else {
                        if (TextUtils.isEmpty(loginRes.getTips())){
                            onFailure(loginRes.getMsg());
                        }else {
                            onFailure(loginRes.getTips());
                        }
                    }
                }else {
                    if (TextUtils.isEmpty(loginRes.getTips())){
                        onFailure(loginRes.getMsg());
                    }else {
                        onFailure(loginRes.getTips());
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtils.showMsg(getContext(), msg);
                o2oQueryHandler.sendEmptyMessageDelayed(2, 5000);
            }
        });
    }
    private int queryNumber;

    private ProgressDialog mProgressDialog;
    private void showWaitDialog(String msg){
        if(mProgressDialog==null)
            return;

        mProgressDialog.setMessage(msg +"(已查询   "+ queryNumber +" 次)" );
        if(mProgressDialog.isShowing()){

        }else{
            mProgressDialog.show();
        }
    }

    private void dissmissWaitDialog(){
        if(mProgressDialog==null || !mProgressDialog.isShowing())
            return;
        mProgressDialog.dismiss();
    }

    public List<String> createHeadByTicket(final PosJHResponse m_hkPayResponse, int count) {
        List<String> list = new ArrayList<>();
        if (pmtId ==2) {
            list.add("支付宝签购单(POS Sale Slip)");
        } else if (pmtId ==3) {
            list.add("微信签购单(POS Sale Slip)");
        } else if (pmtId ==4) {
            list.add("银联二维码(POS Sale Slip)");
        }else {
            list.add("其他签购单"+ m_hkPayResponse.getChannelType());
        }
        if (homeAct.saleType == 1){

            list.add("业务类型:退货" );
        }else {

            list.add("业务类型:销售" );
        }
        list.add("交易时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
        list.add("收款台：" + ErpCommonData.sktno + "  收款员：" + ErpCommonData.loadConfig.getCashierCode());
//        list.add("商户名称:" + m_hkPayResponse.getMerchantName());
        list.add("-----------------------------");
        list.add("流水号：");
        list.add(m_hkPayResponse.getTransactionId());
//        list.add("外部订单号：");
//        list.add(m_hkPayResponse.getOutTradeNo());
        list.add("交易总金额： RMB  "+ m_hkPayResponse.getActTotalFee());
        list.add("-----------------------------");
        list.add("备注：");
        list.add("-----------------------------");
        list.add("本人同意支付以上款项");
        list.add("持卡人签名:");
        list.add("");
        list.add("-----------------------------");
        return list;
    }

    private O2OPayDetail handleO2OData(PosJHResponse posO2oResponse, int type) {
        O2OPayDetail item = new O2OPayDetail();
        item.setTotalFee(MoneyUtils.getMoneyInt(posO2oResponse.getActTotalFee()) + MoneyUtils.getMoneyInt(posO2oResponse.getCouponFee())+ MoneyUtils.getMoneyInt(posO2oResponse.getCouponFee_Shop()) );
        item.setJlbh(mTicket.getOrderNo());
        item.setSktno(mTicket.getSktno());
        if (pmtId ==2){
            item.setPaymentMethod(2);//1 微信  2 支付宝
        }else if (pmtId ==3){
            item.setPaymentMethod(1);//1 微信  2 支付宝
        }
        item.setSkyId(mTicket.getCasherInfo().getPersonId());
        item.setCouponFee(MoneyUtils.getMoneyInt(posO2oResponse.getCouponFee())+ MoneyUtils.getMoneyInt(posO2oResponse.getCouponFee_Shop()));
        item.setTradeType(type);//消费类型
        item.setTransactionId(posO2oResponse.getTransactionId());
        item.setOutTradeNo(posO2oResponse.getOutTradeNo());
//        item.setUserNo(posO2oResponse.get());
        item.setJysj(DateUtils.strToDateLong(posO2oResponse.getOrderTime()));
        item.setPayCode(pmtId);
        return item;
    }

    public void completeTanpay(O2OPayDetail item) {
        int totalZfbMoney = 0;
        if (pmtId ==2){
            mTicket.getO2oZfbList().add(item);
            for(O2OPayDetail o2oItem :mTicket.getO2oZfbList()){
                if(o2oItem.getPayCode() == pmtId ){
                    totalZfbMoney += o2oItem.getTotalFee();
                }
            }
        }else if (pmtId ==3){
            mTicket.getO2oWxList().add(item);
            for(O2OPayDetail o2oItem :mTicket.getO2oWxList()){
                if(o2oItem.getPayCode() == pmtId){
                    totalZfbMoney += o2oItem.getTotalFee();
                }
            }
        }
//        homeAct.reqAddpayNet(totalZfbMoney,false);//请求同步付款接口

        ((PayActivity)homeAct).reqAddPayAndCommitNet(totalZfbMoney, false);//判读是否请求commit
    }


}